package com.bgs.travelapp.login.service.impl;

import com.bgs.travelapp.config.SmsCode;
import com.bgs.travelapp.login.service.LoginService;
import com.bgs.travelapp.result.CommonResult;
import com.bgs.travelapp.user.entity.UserEntity;
import com.bgs.travelapp.user.mapper.UserMapper;
import com.bgs.travelapp.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.DigestUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * 登录模块（前端展示）
 * lzy 2022-7-26 08点47分
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    JavaMailSender mailSender;

    /**
     * 根据手机号发送验证码 （前端展示）
     * lzy 2022-7-26 08点47分
     * @param phone
     * @return
     */
    @Override
    public void sendCodeByPhone(String phone) {
        UserEntity userEntity = new UserEntity();
        userEntity.setPhone(phone);
        List<UserEntity> user = userMapper.select(userEntity);
        if (user.size() > 0) {
            String code = SmsCode.code();
            redisUtil.set(phone,code);
            SmsCode.sendSms(phone,code);
        }
    }

    /**
     * 根据手机号验证登录（前端展示）
     * lzy 2022-7-26 09点05分
     * @param phone
     * @return
     */
    @Override
    public Object loginByPhone(String phone) {
        return null;
    }

    /**
     * 根据账号密码登录（前端展示）
     * lzy 2022-7-26 11点07分
     * @param loginName
     * @param password
     * @return
     */
    @Override
    public CommonResult loginByUser(String loginName, String password) {
        UserEntity userEntity = new UserEntity();
        userEntity.setLoginName(loginName);
        String md5Str = DigestUtils.md5DigestAsHex(password.getBytes());
        userEntity.setPassword(md5Str);
        UserEntity select = userMapper.selectOne(userEntity);
        // 创建时间
        Date createTime = new Date();
        // 时间格式初始化
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String createTimeSdf = sdf.format(createTime);
        String token = Base64Utils.encodeToString((userEntity.getLoginName()+createTimeSdf+userEntity.getPassword()).getBytes());
        if(select != null){
            HashMap<Object, Object> map = new HashMap<>();
            map.put("user", select);
            map.put("token", token);
            return CommonResult.ok(map);
        } else {
            return CommonResult.error("999");
        }
    }

    /**
     * 根据邮箱登录（前端展示）
     * lzy 2022-8-2 14点28分
     * @param mail
     * @param code
     * @return
     */
    @Override
    public CommonResult loginByQQCode(String mail, String code) {
        UserEntity userEntity = new UserEntity();
        userEntity.setMail(mail);
        UserEntity user = userMapper.selectOne(userEntity);
        Object o = redisUtil.get(mail + "login");
        if (code.equalsIgnoreCase((String) o)) {
            // 创建时间
            Date createTime = new Date();
            // 时间格式初始化
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            String createTimeSdf = sdf.format(createTime);
            String token = Base64Utils.encodeToString((user.getLoginName()+createTimeSdf+user.getPassword()).getBytes());
            HashMap<Object, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("user", user);
            return CommonResult.ok(map);
        } else {
            return CommonResult.error("33");
        }
    }

    /**
     * 根据qq邮箱账号发送验证码 （前端展示）
     * lzy 2022-8-2 14点28分
     * @param mail
     * @return
     */
    @Override
    public CommonResult sendCodeByQQMail(String mail) {
        UserEntity userEntity = new UserEntity();
        userEntity.setMail(mail);
        UserEntity user = userMapper.selectOne(userEntity);
        if (user != null) {
            int count = 1;//默认发送一次
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = null;
            try {
                helper = new MimeMessageHelper(mimeMessage, true);
                while (count-- != 0) {
                    String codeNum = "";
                    int[] code = new int[3];
                    Random random = new Random();
                    //自动生成验证码
                    for (int i = 0; i < 6; i++) {
                        int num = random.nextInt(10) + 48;
                        int uppercase = random.nextInt(26) + 65;
                        int lowercase = random.nextInt(26) + 97;
                        code[0] = num;
                        code[1] = uppercase;
                        code[2] = lowercase;
                        codeNum += (char) code[random.nextInt(3)];
                    }
                    //标题4
                    helper.setSubject("您的验证码为：" + codeNum);
                    //内容
                    helper.setText("您好！，感谢支持易游旅行。您的验证码为：" + "<h2>" + codeNum + "</h2>" + "千万不能告诉别人哦！ 五分钟后失效", true);
                    //邮件接收者
                    helper.setTo(mail);
                    //邮件发送者，必须和配置文件里的一样，不然授权码匹配不上
                    helper.setFrom("389641604@qq.com");
                    redisUtil.set(mail + "login", codeNum, 300);
                    mailSender.send(mimeMessage);
                }
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            return CommonResult.ok();
        } else {
            return CommonResult.error("999");
        }
    }

    /**
     * 校验邮箱号是否被绑定（前端展示）
     * lzy 2022-8-2 20点20分
     * @param mail
     * @return
     */
    @Override
    public CommonResult checkMail(String mail) {
        UserEntity userEntity = new UserEntity();
        userEntity.setMail(mail);
        UserEntity user = userMapper.selectOne(userEntity);
        if (user == null) {
            return CommonResult.ok();
        }
        return CommonResult.error("999");
    }

    /**
     * 注册获取验证码（前端展示）
     * lzy 2022-8-2 20点43分
     * @param mail
     * @return
     */
    @Override
    public void sendCodeByQQMailRe(String mail) {
        int count = 1;//默认发送一次
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage, true);
            while (count-- != 0) {
                String codeNum = "";
                int[] code = new int[3];
                Random random = new Random();
                //自动生成验证码
                for (int i = 0; i < 6; i++) {
                    int num = random.nextInt(10) + 48;
                    int uppercase = random.nextInt(26) + 65;
                    int lowercase = random.nextInt(26) + 97;
                    code[0] = num;
                    code[1] = uppercase;
                    code[2] = lowercase;
                    codeNum += (char) code[random.nextInt(3)];
                }
                //标题4
                helper.setSubject("您的验证码为：" + codeNum);
                //内容
                helper.setText("您好！，感谢支持易游旅行。您的验证码为：" + "<h2>" + codeNum + "</h2>" + "千万不能告诉别人哦！ 五分钟后失效", true);
                //邮件接收者
                helper.setTo(mail);
                //邮件发送者，必须和配置文件里的一样，不然授权码匹配不上
                helper.setFrom("389641604@qq.com");
                redisUtil.set(mail + "register", codeNum, 300);
                mailSender.send(mimeMessage);
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 注册用户（前端展示）
     * lzy 2022-8-2 21点06分
     * @param userEntity
     * @param code
     * @return
     */
    @Override
    public CommonResult registerUser(UserEntity userEntity,String code) {
        String mail = userEntity.getMail();
        userEntity.setAvatarId(656);
        userEntity.setCreateTime(new Date());
        Object o = redisUtil.get(mail + "register");
        String md5Str = DigestUtils.md5DigestAsHex(userEntity.getPassword().getBytes());
        userEntity.setPassword(md5Str);
        int i = 0;
        if (code.equalsIgnoreCase((String) o)) {
            i = userMapper.insert(userEntity);
            return CommonResult.ok(i);
        } else {
            return CommonResult.error("999");
        }
    }

}
